/* eslint-disable camelcase */

import React from 'react';
import PropTypes from 'prop-types';

import Dialog from '@kuiper-components/dialog';
import Notification from '@kuiper-components/notification';
import s from './Editor.module.css';
import Content from './Content';

export default function Editor({
	children,
	onSub,
	record,
	alertGroupBalance,
	isDefault,
	...props
}) {
	const [dialogVisible, setDialogVisible] = React.useState(false);
	const handleClose = () => {
		setDialogVisible(false);
	};
	const submit = () => {
		setDialogVisible(false);
		onSub && onSub();
	};
	return (
		<>
			{React.cloneElement(children, {
				...children.props,
				onClick(e) {
					if (alertGroupBalance <= 0) {
						Notification.error({
							message: '已超出最大告警策略数，无法继续添加。',
							placement: 'top',
							style: { width: '22rem' },
						});
						return;
					}
					if (children.props.onClick) children.props.onClick(e);
					setDialogVisible(true);
				},
			})}
			<Dialog
				visible={dialogVisible}
				destroyOnClose={true}
				title={record ? '编辑告警策略' : '添加告警策略'}
				wrapClassName={s.dialog}
				{...props}
				onClose={handleClose}
				maskStyle={{ zIndex: 100 }}
			>
				{dialogVisible && (
					<Content
						onClose={handleClose}
						record={record}
						isDefault={isDefault}
						submit={submit}
						{...props}
					/>
				)}
			</Dialog>
		</>
	);
}

Editor.propTypes = {
	receiver: PropTypes.shape({
		name: PropTypes.string.isRequired,
	}),
	children: PropTypes.element.isRequired,
	onSub: PropTypes.func,
	update: PropTypes.func.isRequired,
	record: PropTypes.any,
	receivers: PropTypes.arrayOf(
		PropTypes.shape({
			_id: PropTypes.string.isRequired,
			name: PropTypes.string.isRequired,
		})
	),
	wechat: PropTypes.shape({
		nickname: PropTypes.string,
		wx_openid: PropTypes.string,
	}),
	defaultReceiver: PropTypes.shape({
		_id: PropTypes.string,
	}),
	isDefault: PropTypes.bool,
	alertGroupBalance: PropTypes.number,
};

Editor.defaultProps = {
	receivers: [],
	isDefault: false,
};
